package models;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;


import play.db.ebean.Model;

/*
 * Cart model class.
 * Author: Axakalov Sundet
 */

@Entity
public class Cart extends Model {
	@Id
	public Long id;
	
	@OneToMany(mappedBy="cart", cascade = CascadeType.ALL, orphanRemoval=true)
	public List<CartItem> items;

	@OneToOne(mappedBy="cart")
	public User user;
	
	public boolean isTemp = false;
	
	public static Finder<Long, Cart> find = new Finder<Long, Cart>(Long.class, Cart.class);
	
	public static Cart create(User user)
	{
		Cart cart = new Cart();
		cart.user = user;
		return cart;
	}
	
	public static Cart mergeCarts(Cart mergeTo, Cart cart)
	{	
		for(int i = 0; i < cart.items.size(); i++)
		{
			CartItem item = CartItem.create(cart.items.get(i).product, cart.items.get(i).quantity);
			item.save();
			for(int j = 0; j < mergeTo.items.size(); j++)
			{
				if(item.product.id == mergeTo.items.get(j).product.id)
				{
					CartItem mitem = mergeTo.items.get(j);
					if(item.quantity + mitem.quantity > Product.find.byId(item.product.id).quantity)
						item.quantity = Product.find.byId(item.product.id).quantity;
					else
						item.quantity += mitem.quantity;
					mergeTo.items.remove(j);
				}
			}
			mergeTo.items.add(item);			
		}
		/*
		boolean contains;
		for(CartItem i : cart.items)
		{
			contains = false;
			for(int j = 0; j < mergeTo.items.size(); j++)
			{
				CartItem k = mergeTo.items.get(j);
				if(i.product.id == k.product.id)
				{
					contains = true;
					k.quantity += i.quantity;
					if(k.quantity > Product.find.byId(k.product.id).quantity)
						k.quantity = Product.find.byId(k.product.id).quantity;
					mergeTo.items.set(j, k);
				}
			}
			if(!contains)
			{
				mergeTo.items.add(i);
				mergeTo.save();
			}
		}
		*/
		cart.delete();
		return mergeTo;
	}
}